import React, {useState, useEffect} from "react";
import {Modal, Tree, Tag, Card, Input, Button} from "antd";
import _remove from 'lodash/remove';
import _isEmpty from 'lodash/isEmpty';
import _findIndex from 'lodash/findIndex';
import {connect} from "dva";
import styles from "./CustomTitle.less";

const {TreeNode} = Tree;
const CustomTitle = (props) => {

  const {
    customTitleVisible,
    handleOk,
    handleCancel,
    dispatch,
    customTitle,  // 回显数据
    customTitleList, // 原始数据
    handleChangeProperties,
    selectedModel,
  } = props;

  const [selectedItems, setSelectedItems] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [inputValue, setInputValue] = useState('');


  useEffect(() => {

    dispatch({
      type: 'FlowHandle/getCustomTitleList',
    });
  }, [])


  useEffect(() => {
    const checkedItems = [];
    customTitle.map(item => {
      if (item.titleCode.indexOf('custom_') === -1) {
        checkedItems.push(item.key);
      }

      return item;
    })
    setSelectedItems((customTitle));
    setCheckedKeys(checkedItems);
  }, [customTitle]);


  const onCheck = keys => {
    // 处理移除的节点

    const tmpList = [...selectedItems];
    checkedKeys.map(key => {
      if (keys.indexOf(key) === -1) {
        _remove(tmpList, (item) => {
          return item.key === key;
        })
      }
      return key;
    })

    setCheckedKeys(keys);


    keys.map(key => {
      customTitleList.map(item => {
        const {children} = item;
        children.map(subItem => {
            if (subItem.key === key) {
              if (_findIndex(tmpList, (e) => {return e.key === key}) === -1) {
                tmpList.push(subItem);
              }
            }
            return subItem;
          }
        )
        return item;
      })
      return key;
    })

    setSelectedItems(tmpList);
  };


  const renderTreeNodes = (data=[]) =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode {...item} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });

  const handleClose = (key) => {
    _remove(selectedItems, (item) => {
      return item.key === key;
    })
    setSelectedItems([...selectedItems]);
    _remove(checkedKeys, (tmpKey) => {
      return tmpKey === key;
    })
    setCheckedKeys([...checkedKeys])


  }


  const handleAdd = () => {
    if (_isEmpty(inputValue)) {
      return;
    }
    const tmpValue = {
      key: inputValue,
      titleName: inputValue,
      titleExpression: `@{${inputValue}}`,
      titleType: "uuid",
      titleCode: `custom_${inputValue}`,
    }


    selectedItems.push(tmpValue);
    setSelectedItems([...selectedItems]);

    setInputValue('')
  }

  const okAction = () => {
    handleChangeProperties(
      'customTitle',
      selectedItems,
      selectedModel.model,
      selectedModel.shape,
      false,
    );
    handleOk();
  }

  return (
    <Modal
      destroyOnClose
      title="自定义标题"
      visible={customTitleVisible}
      onOk={okAction}
      onCancel={handleCancel}
    >
      <div className={styles.root}>

        <Card>
          <div className={styles.selected}>

            {selectedItems.map(item => {
              return (
                <div style={{marginBottom: '10px'}}>
                  <Tag
                    key={item.key}
                    closable
                    onClose={e => {
                      e.preventDefault();
                      handleClose(item.key);
                    }}
                  >
                    {item.titleName}
                  </Tag>
                </div>
              )
            })}
          </div>

          <div className={styles.addcontent}>
            <Input
              style={{flex: 1, marginLeft: '10px', marginRight: '10px'}}
              placeholder='请输入自定义标题'
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
            />
            <Button type='primary' onClick={handleAdd}>添加</Button>
          </div>
        </Card>
        <div style={{marginTop: '10px'}}>

          <Tree
            checkable
            checkedKeys={checkedKeys}
            onCheck={onCheck}
          >
            {renderTreeNodes(customTitleList)}
          </Tree>
        </div>
      </div>
    </Modal>
  );
}


export default connect()(CustomTitle);




